<?php

namespace app\admin\controller;

use think\Request;
use app\admin\model\User as UserModel;
use app\admin\validate\User as UserValidate;
use think\Db;

class User extends AdminController
{

    private $userModel = null;
    private $userValidate = null;

    public function _initialize()
    {
        // 实例化用户模型
        $this->userModel = new UserModel();
        $this->userValidate = new UserValidate();
    }

	/**
     * [index 会员管理列表]
     * @return [type] [description]
     */
	public function index(Request $request)
	{
        // 判断是否存在搜索
        if ( $request->isPost() ) {
            // 查询分页数据（有搜索）
            $search = $request->post('search');
            $list = UserModel::field(array('uid','username','email','tel','level','status','createTime'))->where(array('status'=>1, 'tel'=>$search))->order('createTime DESC')->paginate(10,false,[
                'type' => 'bootstrap',
                'var_page' => 'page'
            ]);
        } else {
            // 查询分页数据（无搜索）
            $list = UserModel::field(array('uid','username','email','tel','level','status','createTime'))->where(array('status'=>1))->order('createTime DESC')->paginate(10,false,[
                'type' => 'bootstrap',
                'var_page' => 'page'
            ]);
        }
        
        // 获取分页显示
        $page = $list->render();
        // 模板赋值
        $this->assign('list', $list);
        $this->assign('page', $page);
	    // 模板渲染
    	return $this->fetch('index');
	}


    /**
     * [create 新增会员]
     * @return [type] [description]
     */
    public function create()
    {
        // 生成随机用户名
        $username = 'XT'.substr(uniqid(md5(microtime())), 0, 10);
        $this->assign('username', $username);
        return $this->fetch('add');
    }

    public function save(Request $request)
    {
        // 依赖注入的方式
        $post = $request->post();
        // 调用验证器类，数据验证
        if ( !$this->userValidate->scene('create')->check($post) ) {
            $this->error($this->userValidate->getError());
        }
        // 验证密码
        if ( $post['password'] != $post['repassword'] ) {
            $this->error('两次密码输入不一致');
        }

        // 组合最终注册数据
        $post['createTime'] = time();
        $post['password'] = md5($post['password']);

        // 传入数据到Model中
        $this->userModel->data($post);

        // 过滤非数据表的字段,并写入数据, 返回写入记录数量
        $result = $this->userModel->allowField(true)->save();
        // 判断跳转
        if ($result > 0) {
            return $this->success('添加成功', url('admin/user/index'));
        } else {
            return $this->error('添加失败');
        }
    }


	/**
     * [edit 会员信息编辑页面]
     * @param  [type] $uid [用户ID]
     * @return [type]      [模版]
     */
	public function edit($uid)
	{
	    // 静态创建模型对象
		$res = UserModel::get($uid)->getData();
        $this->assign('res',$res);
		return $this->fetch('edit');
	}


	/**
     * [update 会员信息修改保存]
     * @param  Request $request [请求类注入]
     * @param  [type]  $uid     [用户ID]
     * @return [type]           [description]
     */
	public function update(Request $request, $uid)
	{
        // 接收
        $post = $request->post();
        // 调用验证器类，数据验证
        if ( !$this->userValidate->scene('update')->check($post) ) {
            $this->error($this->userValidate->getError());
        }
		// 执行更新
        $res = $this->userModel->allowField(true)->save($post, array('uid'=>$uid));
        // 更新结果
    	if ( !$res ) {
    		$this->error('更新失敗');
    	} else {
            $this->success('更新成功', url('admin/user/index'));
        }
	}


    /**
     * [updatePass 修改密码]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function updatePass(Request $request)
    {

        if ( $request->isPost() ) {
            $post = $request->post();
             // 调用验证器类，数据验证
            if ( !$this->userValidate->scene('updatePass')->check($post) ) {
                $this->error($this->userValidate->getError());
            }
            if( $post['password'] != $post['repassword'] ){
                $this->error('两次密码输入不一致');
            }
            $post['password'] = md5($post['password']);
            // 执行更新
            $res = $this->userModel->allowField(true)->save($post, array('uid'=>$post['uid']));
            // 更新结果
            if ( !$res ) {
                $this->error('密码更新失敗');
            } else {
                $this->success('密码更新成功', url('admin/user/index'));
            }

        } else {

            $uid = $request->param('uid');
            if( !$uid ) $this->error('会员ID不存在');
            $this->assign('uid', $uid);
            return $this->fetch('editPass');

        }

    }


	// 执行删除操作
	public function delete($uid)
    {
        $result = UserModel::get($uid)->delete();

        if ($result > 0) {
            $info['status'] = true;
            $info['uid'] = $uid;
            $info['info'] = 'ID为:'.$uid.'的用户删除成功!';
        } else {
            $info['status'] = false;
            $info['uid'] = $uid;
            $info['info'] = 'ID为:'.$uid.'的用户删除失败!';
        }
        return json($info);
    }


    /**
     * [info 会员详情]
     * @return [type] [description]
     */
    public function info($uid)
    {
        if( !$uid ) $this->error('会员ID不存在！');
        // $info = UserModel::get($uid)->getData();
        // dump($info);
        // $db = new Db();
        // dump($db);die;
        $data=Db::field('fullname','nickname','age','sex','headPic','birthday','qq')
                ->table(['xt_user'=>'u','xt_user_more'=>'m'])
                ->where('u.uid = m.uid AND  u.status = 1')//查询条件语句
                ->select();
        dump($data);
    }


}